/*
 * @Date: 2022-09-14 17:41:27
 * @LastEditTime: 2023-02-15 17:11:42
 * @Description: 下拉选择组件
 */
import { defineComponent, reactive, ref, watch } from 'vue'
import axios from "@/axios";
import {getByPath, zdMcByDm} from "@/utils/common"
import { assignDeep } from "@/utils/common";
import classes from './index.module.scss';
import * as _ from 'lodash'
import { Search } from '@element-plus/icons-vue';
import {types} from "sass";
import Boolean = types.Boolean;
export default defineComponent({
    name: 'MyDownList',
    inheritAttrs: false,
    props: {
        /**
         * 输入值
         */
        modelValue: {
            type: String
        },
        /**
         * 显示名称
         */
        showName:{
            type: String
        },
        /**
         * 字典类别
         */
        zdlb: {
            type: String,
            required: true
        },
        /**
         * 表格配置集
         */
        gridOptions: {
            type: Object,
            default: {}
        },
        /**
         * 搜索参数，与默认参数合并
         */
        searchParams: {
            type: Object,
            default: { yobj: {} }
        },
        disabled: {
            type: Boolean
        },
        readonly: {
            type: Boolean
        },
        isResult:{
            type: Boolean,
            default: false
        }
    },
    emits: ["update:modelValue", "change", "result"],
    setup(props, context) {
        const myData: any = reactive({
            /**
             * 绑定输入框值
             */
            value: "",
            /**
             * 数据加载中
             */
            loading: false,
            /**
             * 列定义
             */
            tableColumn: [
                { type: 'seq', width: 50, title: '序号', align: 'center' },
                { field: 'dm', width: 180, title: '代码' },
                { field: 'mc', title: '名称' }
            ],
            /**
             * 表格数据
             */
            tableData: [],
            /**
             * 分页配置
             */
            tablePage: {
                pageSizes: [5, 10, 20, 50],
                total: 0,
                currentPage: 1,
                pageSize: 5,
                layouts: ['Sizes', 'PrevJump', 'PrevPage', 'NextPage', 'NextJump', 'FullJump', 'Total']
            },
            /**
             * 搜索参数-默认
             */
            searchParamsDefault: {
                yobj: {
                    zdlb: props.zdlb
                },
                page: {
                    pageSize: 5,
                    totalRequired: true
                },
                sys: {
                    authCode: "QTQX_ZDGL",
                    cllx: "zdSearch"
                }
            },
            searchParams: {
                sys: {
                    searchKey: ""
                },
                page: {
                    pageNumber: 1,
                    totalRequired: true,
                    pageSize: 5,
                },
                yobj:{}
            },
            disabled: props.disabled,
            readonly: props.readonly,
            isdisabled: props.readonly || props.disabled,
        });
        const xSelect = ref();
        const debounceSearchList = _.debounce(() => searchList(), 700);
        const searchList = () => {
            if (myData.searchParams.sys.searchKey && myData.searchParams.sys.searchKey.charAt(0) === '=') {
                myData.searchParams.sys.searchKey = myData.searchParams.sys.searchKey.slice(1)
                myData.searchParams.sys.jqss = '1'
            } else {
                myData.searchParams.sys.jqss = '0'
            }
            console.log("搜索参数", myData.searchParams.sys.searchKey)

            myData.loading = true
            myData.searchParams.page.pageNumber = myData.tablePage.currentPage
            axios.post(myData.searchParams, { tloading: false }).then(req => {
                myData.tableData = req.data.list
                if (getByPath(myData.searchParams, "sys.pageCllx") === "select") {
                    myData.tableData.push({
                        dm: "my-null",
                        mc: "为空"
                    });
                    myData.tableData.push({
                        dm: "my-not-null",
                        mc: "非空"
                    });
                }
                myData.loading = false
                if (myData.searchParams.page.totalRequired) {
                    myData.tablePage.total = req.data.totalRow;
                }
            })
        }
        /**
         * 监听input框值改变事件
         * @param value 值
         * @param $event
         */
        const inputChangeEvent = (value: string) => {
            myData.tablePage.currentPage = 1
            myData.searchParams.page.totalRequired = true
            debounceSearchList()
        }
        /**
         * 翻页操作
         * @param currentPage 当前页
         * @param pageSize 页大小
         */
        const pageChangeEvent = ({ currentPage, pageSize }: any) => {
            myData.tablePage.currentPage = currentPage
            myData.tablePage.pageSize = pageSize
            myData.searchParams.page.pageSize = pageSize
            myData.searchParams.page.totalRequired = false
            searchList();
        }
        /**
         * 失去焦点
         * @param event
         */
        const hidePanelClick = (event: any) => {
            //恢复输入框的值为用户当前选择的值的翻译结果
            modelValueWatch(props.modelValue, null);
            //清除搜索条件
            myData.searchParams.sys.searchKey = "";
            myData.search = "";
            myData.tablePage.currentPage = 1;
        }
        /**
         * 在点击尾部图标时触发该事件
         */
        const clearClick = () => {
            context.emit('update:modelValue', "");
            context.emit('change', undefined);
        }
        /**
         * 选中操作
         * @param row 选中的行
         */
        const cellClickEvent = ({ row }: any) => {
            //将选中的值返回给父组件
            context.emit('update:modelValue', row.dm);
            context.emit('change', row);
            xSelect.value.blur()
        }
        /**
         * 监听值变化的方法
         * @param newVal 新值
         * @param oldVal 旧值
         */
        const modelValueWatch = function (newVal: any, oldVal: any) {
            if (!newVal) {
                //如果新值为空
                myData.value = "";
                return
            }
            if (newVal === 'my-null') {
                myData.value = "为空";
            } else if (newVal === 'my-not-null') {
                myData.value = "非空";
            } else if(props.isResult){
                axios.post(assignDeep({}, myData.searchParamsDefault, props.searchParams,{yobj:{dm: newVal}})).then(req => {
                    let zd = req.data.list[0];
                    myData.value = zd.mc;
                    context.emit("result", zd)
                })
            } else if (props.showName) {
                myData.value = props.showName;
            } else {
                zdMcByDm(props.zdlb, newVal).then((req:any)=>{
                    myData.value = req;
                });
            }
        }

        const visibleChange = (val: boolean) => {
            if (val) {
                myData.searchParams = assignDeep({}, myData.searchParamsDefault,myData.searchParams, props.searchParams);
                myData.tablePage.currentPage = 1
                myData.tablePage.pageSize = 5
                searchList()
            }
        }

        if (props.modelValue) {
            //如果初始传入了值，则主动调用值的监听方法
            modelValueWatch(props.modelValue, null);
        }
        /**
         * 监听传入的值的变化
         */
        watch(() => props.modelValue, modelValueWatch);
        /**
         * 监听搜索参数变化
         */
        watch(() => props.searchParams, (newVal) => {
            myData.searchParams = assignDeep({}, myData.searchParamsDefault,myData.searchParams, newVal);
        })
        watch(() => props.zdlb, (newVal) => {
            myData.searchParams.yobj.zdlb = newVal;
        })

        watch(() => props.disabled, (newValue) => {
            myData.isdisabled = props.readonly || newValue
        })
        watch(() => props.readonly, (newValue) => {
            myData.isdisabled = props.disabled || newValue
        })

        /**
         * 返回值
         */
        return {
            myData,
            xSelect,
            inputChangeEvent,
            clearClick,
            cellClickEvent,
            pageChangeEvent,
            hidePanelClick,
            visibleChange
        }
    },
    render() {
        return (
            <el-select ref="xSelect" class={classes.elInput} disabled={this.myData.isdisabled} small="small" v-model={this.myData.value} onClear={this.clearClick} clearable onVisibleChange={this.visibleChange}
                v-slots={{
                    empty: () => {
                        return (<div class={classes.myDropdown}>
                            <div style="padding:4px">
                                <el-input class={classes.elInput} small="small" v-model={this.myData.searchParams.sys.searchKey} ref="sInput" clearable prefix-icon={Search} onInput={this.inputChangeEvent}></el-input>
                            </div>
                            <vxe-grid
                                auto-resize
                                height="auto"
                                max-height="252px"
                                loading={this.myData.loading}
                                pager-config={this.myData.tablePage}
                                data={this.myData.tableData}
                                columns={this.myData.tableColumn}
                                onCell-click={this.cellClickEvent}
                                onPage-change={this.pageChangeEvent}
                                {...this.gridOptions}>
                            </vxe-grid>
                        </div>)
                    }
                }}>
            </el-select>
        )
    }
})
